﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.Net;
using System.IO;
using System.Web.Script.Serialization;

namespace DoubanFM_Downloader
{
    public class JsonToDictionary
    {
        HttpWebRequest request;
        HttpWebResponse response;

        #region Json反序列化
        public Dictionary<string, object> getDictionary(string url)
        {
            string resultJson;
            try
            {
                //初始化请求地址
                request = WebRequest.Create(url) as HttpWebRequest;
                //初始化请求的head
                request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
                request.Method = "GET";
                request.UserAgent = "Mozilla/4.0";
                response = (HttpWebResponse)request.GetResponse();
                //转成流对象 
                Stream responseStream = response.GetResponseStream();
                StreamReader responseReader = new StreamReader(responseStream);
                //读出转成字符串
                resultJson = responseReader.ReadToEnd();
                response.Close();

                //实例化JavaScriptSerializer类的新实例
                JavaScriptSerializer JSS = new JavaScriptSerializer();
                try
                {
                    //将指定的 JSON 字符串转换为 Dictionary<string, object> 类型的对象
                    return JSS.Deserialize<Dictionary<string, object>>(resultJson);
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
            }
            catch
            {
                return null;
            }
        }
        #endregion
    }
}
